'use client'

import { useState, useEffect } from 'react'
import { 
  DocumentTextIcon,
  MagnifyingGlassIcon,
  ClipboardDocumentIcon,
  SparklesIcon
} from '@heroicons/react/24/outline'
import TextRewriteModal from '@/components/TextRewriteModal'
import Pagination from '@/components/Pagination'

interface CopywritingItem {
  id: number
  videoId: string
  title: string | null
  author: string | null
  tags: string | null
  createdAt: string
  extractionId: number
  extractedText: string
  extractionMethod: string
  extractionDate: string
  rewriteId?: number
  rewrittenText?: string
  rewriteStyle?: string
  rewriteTone?: string
  rewriteLength?: string
  rewriteRequirements?: string
  rewriteDate?: string
}

interface Toast {
  message: string
  type: 'success' | 'error' | 'info'
}

export default function CopywritingPage() {
  const [copywritingItems, setCopywritingItems] = useState<CopywritingItem[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [toast, setToast] = useState<Toast | null>(null)
  const [selectedItems, setSelectedItems] = useState<number[]>([])
  const [isRewriteModalOpen, setIsRewriteModalOpen] = useState(false)

  // 分页状态
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0,
    hasNext: false,
    hasPrev: false
  })

  // 获取文案数据
  const fetchCopywritingData = async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams({
        page: pagination.page.toString(),
        pageSize: pagination.pageSize.toString(),
        search: searchTerm
      })

      const response = await fetch(`/api/copywriting/list?${params}`)
      const data = await response.json()

      if (data.success) {
        setCopywritingItems(data.items)
        setPagination(prev => ({
          ...prev,
          ...data.pagination
        }))
      } else {
        showToast('获取数据失败', 'error')
      }
    } catch (error) {
      showToast('网络错误，请重试', 'error')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchCopywritingData()
  }, [pagination.page, searchTerm])

  // Toast通知函数
  const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
    setToast({ message, type })
    setTimeout(() => setToast(null), 3000)
  }

  // 复制文案
  const copyText = (text: string, type: string) => {
    navigator.clipboard.writeText(text)
    showToast(`${type}已复制到剪贴板`, 'success')
  }

  // 选择/取消选择文案
  const toggleItemSelection = (extractionId: number) => {
    setSelectedItems(prev =>
      prev.includes(extractionId)
        ? prev.filter(id => id !== extractionId)
        : [...prev, extractionId]
    )
  }

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedItems.length === copywritingItems.length) {
      setSelectedItems([])
    } else {
      setSelectedItems(copywritingItems.map(item => item.extractionId))
    }
  }

  // 批量改写文案
  const handleBatchRewrite = async (options: {prompt: string}) => {
    if (selectedItems.length === 0) {
      showToast('请先选择要改写的文案', 'error')
      return
    }

    if (!options.prompt.trim()) {
      showToast('请输入改写提示词', 'error')
      return
    }

    try {
      showToast(`正在改写 ${selectedItems.length} 个文案...`, 'info')

      const response = await fetch('/api/copywriting/rewrite', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          extractionIds: selectedItems,
          prompt: options.prompt
        }),
      })

      const data = await response.json()

      if (data.success) {
        showToast(data.message, 'success')
        setSelectedItems([]) // 清空选择
        setIsRewriteModalOpen(false) // 关闭模态框

        // 10秒后自动刷新
        setTimeout(() => {
          fetchCopywritingData()
          showToast('页面已自动刷新，请查看改写结果', 'info')
        }, 10000)
      } else {
        showToast(data.error || '改写失败', 'error')
      }
    } catch (error) {
      showToast('网络错误，请重试', 'error')
    }
  }

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchTerm(value)
    setPagination(prev => ({ ...prev, page: 1 })) // 搜索时重置到第一页
  }

  // 分页处理
  const handlePageChange = (newPage: number) => {
    setPagination(prev => ({ ...prev, page: newPage }))
    setSelectedItems([]) // 换页时清空选择
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
        <span className="ml-2 text-gray-600">加载中...</span>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="sm:flex sm:items-center sm:justify-between">
        <div className="sm:flex-auto">
          <h1 className="text-xl font-semibold text-gray-900">文案管理</h1>
          <p className="mt-2 text-sm text-gray-700">
            管理已提取的视频文案和改写结果
          </p>
        </div>

        {/* 批量操作按钮 */}
        {selectedItems.length > 0 && (
          <div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none flex space-x-3">
            <button
              onClick={() => setIsRewriteModalOpen(true)}
              className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500"
            >
              <SparklesIcon className="-ml-0.5 mr-2 h-4 w-4" />
              改写文案 ({selectedItems.length})
            </button>
          </div>
        )}
      </div>

      {/* 搜索框和批量操作 */}
      <div className="flex items-center justify-between">
        <div className="max-w-md">
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => handleSearch(e.target.value)}
              className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500"
              placeholder="搜索标题、作者、标签或文案内容..."
            />
          </div>
        </div>

        {/* 全选按钮 */}
        {copywritingItems.length > 0 && (
          <button
            onClick={toggleSelectAll}
            className="text-sm text-indigo-600 hover:text-indigo-800"
          >
            {selectedItems.length === copywritingItems.length ? '取消全选' : '全选'}
          </button>
        )}
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white overflow-hidden shadow rounded-lg">
          <div className="p-5">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <DocumentTextIcon className="h-6 w-6 text-gray-400" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">
                    文案总数
                  </dt>
                  <dd className="text-lg font-medium text-gray-900">
                    {copywritingItems.length}
                  </dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white overflow-hidden shadow rounded-lg">
          <div className="p-5">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <SparklesIcon className="h-6 w-6 text-gray-400" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">
                    已改写
                  </dt>
                  <dd className="text-lg font-medium text-gray-900">
                    {copywritingItems.filter(item => item.rewriteId).length}
                  </dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white overflow-hidden shadow rounded-lg">
          <div className="p-5">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ClipboardDocumentIcon className="h-6 w-6 text-gray-400" />
              </div>
              <div className="ml-5 w-0 flex-1">
                <dl>
                  <dt className="text-sm font-medium text-gray-500 truncate">
                    搜索结果
                  </dt>
                  <dd className="text-lg font-medium text-gray-900">
                    {pagination.total}
                  </dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 文案列表 */}
      <div className="bg-white shadow overflow-hidden sm:rounded-md">
        <ul className="divide-y divide-gray-200">
          {copywritingItems.length === 0 ? (
            <li className="px-6 py-8 text-center">
              <DocumentTextIcon className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">暂无文案数据</h3>
              <p className="mt-1 text-sm text-gray-500">
                {searchTerm ? '没有找到匹配的文案' : '还没有提取过文案的视频'}
              </p>
            </li>
          ) : (
            copywritingItems.map((item) => (
              <li key={`${item.id}-${item.extractionId}`} className={`px-6 py-4 ${selectedItems.includes(item.extractionId) ? 'bg-blue-50' : ''}`}>
                <div className="space-y-4">
                  {/* 视频信息和选择框 */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3 flex-1">
                      <input
                        type="checkbox"
                        checked={selectedItems.includes(item.extractionId)}
                        onChange={() => toggleItemSelection(item.extractionId)}
                        className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                      />
                      <div className="flex-1">
                        <h3 className="text-sm font-medium text-gray-900 line-clamp-1">
                          {item.title || `视频 ${item.videoId}`}
                        </h3>
                        <div className="mt-1 flex items-center space-x-4 text-xs text-gray-500">
                          {item.author && (
                            <span>👤 {item.author}</span>
                          )}
                          <span>📅 {new Date(item.createdAt).toLocaleDateString()}</span>
                          <span>🔤 {item.extractionMethod === 'aliyun_sensevoice' ? '语音识别' : item.extractionMethod}</span>
                        </div>

                        {/* 标签显示 */}
                        {item.tags && (
                          <div className="mt-2 flex flex-wrap gap-1">
                            {item.tags.split(',').map((tag, index) => (
                              <span
                                key={index}
                                className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-indigo-100 text-indigo-800"
                              >
                                🏷️ {tag.trim()}
                              </span>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 文案对比显示 */}
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {/* 原始文案 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center space-x-2">
                          <DocumentTextIcon className="h-4 w-4 text-gray-500" />
                          <span className="text-sm font-medium text-gray-700">原始文案</span>
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                            {new Date(item.extractionDate).toLocaleDateString()}
                          </span>
                        </div>
                        <button
                          onClick={() => copyText(item.extractedText, '原始文案')}
                          className="text-xs text-blue-600 hover:text-blue-800 flex items-center space-x-1"
                        >
                          <ClipboardDocumentIcon className="h-3 w-3" />
                          <span>复制</span>
                        </button>
                      </div>
                      <p className="text-sm text-gray-800 leading-relaxed">
                        {item.extractedText}
                      </p>
                    </div>

                    {/* 改写文案 */}
                    <div className={`rounded-lg p-4 ${item.rewriteId ? 'bg-orange-50' : 'bg-gray-100'}`}>
                      {item.rewriteId ? (
                        <>
                          <div className="flex items-center justify-between mb-3">
                            <div className="flex items-center space-x-2">
                              <SparklesIcon className="h-4 w-4 text-orange-500" />
                              <span className="text-sm font-medium text-gray-700">改写文案</span>
                              <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-100 text-orange-800">
                                {item.rewriteStyle}
                              </span>
                              <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                {item.rewriteTone}
                              </span>
                            </div>
                            <button
                              onClick={() => copyText(item.rewrittenText!, '改写文案')}
                              className="text-xs text-orange-600 hover:text-orange-800 flex items-center space-x-1"
                            >
                              <ClipboardDocumentIcon className="h-3 w-3" />
                              <span>复制</span>
                            </button>
                          </div>
                          <p className="text-sm text-gray-800 leading-relaxed mb-2">
                            {item.rewrittenText}
                          </p>
                          <div className="flex items-center justify-between text-xs text-gray-500">
                            <span>📅 {new Date(item.rewriteDate!).toLocaleDateString()}</span>
                            {item.rewriteRequirements && (
                              <span className="bg-white px-2 py-1 rounded">
                                💡 {item.rewriteRequirements}
                              </span>
                            )}
                          </div>
                        </>
                      ) : (
                        <div className="flex items-center justify-center h-full text-gray-400">
                          <div className="text-center">
                            <SparklesIcon className="h-8 w-8 mx-auto mb-2" />
                            <p className="text-sm">暂未改写</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </li>
            ))
          )}
        </ul>

        {/* 分页组件 */}
        <Pagination
          currentPage={pagination.page}
          totalPages={pagination.pages}
          totalItems={pagination.total}
          pageSize={pagination.pageSize}
          onPageChange={handlePageChange}
          hasNext={pagination.hasNext}
          hasPrev={pagination.hasPrev}
        />
      </div>

      {/* 文案改写模态框 */}
      <TextRewriteModal
        isOpen={isRewriteModalOpen}
        onClose={() => setIsRewriteModalOpen(false)}
        onRewrite={handleBatchRewrite}
        selectedCount={selectedItems.length}
      />

      {/* Toast通知 */}
      {toast && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-2 rounded-md shadow-lg ${
          toast.type === 'success' ? 'bg-green-500 text-white' :
          toast.type === 'error' ? 'bg-red-500 text-white' :
          'bg-blue-500 text-white'
        }`}>
          {toast.message}
        </div>
      )}
    </div>
  )
}
